using System.Collections.Generic;
using Godot;

namespace MonsterDiKe.common;

/**
 * 状态机-基类
 */
public partial class StateMachine : Node
{

    private List<BaseState> _baseStates;

    private BaseState _prevState;

    private BaseState _curState;
    
    
    public override void _Ready()
    {
        /*
         * 禁用进程 如：_Process(double delta) || _PhysicsProcess(double delta)
         * 后续调用 ProcessModeEnum.Inherit 恢复
         */
        ProcessMode = ProcessModeEnum.Disabled;
    }

    public override void _Process(double delta)
    {
        UpdateState(_curState.Process(delta));
    }

    public override void _PhysicsProcess(double delta)
    {
        UpdateState(_curState.PhysicsProcess(delta));
    }

    public override void _UnhandledInput(InputEvent @event)
    {
        UpdateState(_curState.HandleInput(@event));
    }

    /**
     * 初始化状态机
     * @param node 状态机父节点
     */
    public void Init()
    {
        /*
         * 将状态机子节点添加到列表中
         */
        _baseStates = new List<BaseState>(0);
        foreach (Node child in GetChildren())
        {
            if (child is BaseState state)
            {
                _baseStates.Add(state);
            }
        }
        
        if(_baseStates.Count <= 0) return;
        BaseState.StateMachine = this;
        
        /*
         * 1、初始化每个状态机
         * 2、设置第一个状态为当前状态
         * 3、启动进程
         */
        foreach (BaseState state in _baseStates)
        {
            state.Init();
        }
        UpdateState(_baseStates[0]);
        ProcessMode = ProcessModeEnum.Inherit;
    }

    private void UpdateState(BaseState newState)
    {
        if (newState is null || newState == _curState)
        {
            return;
        }
        
        // 当前状态不为null则执行退出事件
        _curState?.Exit();
        
        // 更新状态
        _prevState = _curState;
        _curState = newState;
        _curState.Enter();
    }


}